<template>
	<!-- 对话框（物品详情） -->
	<el-dialog v-model="visibleInner" append-to-body center destroy-on-close draggable width="75%" @close="dialogClosed">
		<el-descriptions v-loading="loading" :column="4" :title="_item.itemName" border>
			<template #extra>
				<div style="margin-top: 10px">
					相关配方：
					<el-button-group size="small">
						<el-button @click="toRecipe('asProduct')">作为产物</el-button>
						<el-button @click="toRecipe('asMaterial')">作为原料</el-button>
					</el-button-group>
				</div>
			</template>
			<el-descriptions-item :span="1">
				<template #label>
					图片
				</template>
				<el-image v-if="_item.image" :src="getImage(_item.image)" fit="contain" style="width: 128px; height: 128px"></el-image>
			</el-descriptions-item>
			<el-descriptions-item :span="3">
				<template #label>
					描述
				</template>
				<div class="pre-wrap">{{ _item.description }}</div>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					全类别
				</template>
				<el-tag>{{ _item.classificationNameList?.join(' / ') }}</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					物理形态
				</template>
				<el-tag>{{ _item.fluid === 0 ? '固体' : '流体' }}</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					堆叠数量
				</template>
				<el-tag>{{ _item.stack }}</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					装备部位
				</template>
				<el-tag :type="_item.equipmentLocation !== 0 ? undefined : 'info'">
					{{ _item.equipmentLocation === 1 ? '手部' : (_item.equipmentLocation === 2 ? '身体' : '/') }}
				</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					能否手搓
				</template>
				<el-tag :type="_item.handmade === 1 ? undefined : 'info'">{{ _item.handmade === 1 ? '能' : '不能' }}</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					能量
				</template>
				<el-tag :type="(_item.energy && _item.energy > -1) ? undefined : 'info'">{{ (_item.energy && _item.energy > -1) ? `${_item.energy} MJ` : '/' }}</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					资源槽点数
				</template>
				<el-tag :type="(_item.resourceSinkPoints && _item.resourceSinkPoints > -1) ? undefined : 'info'">{{
						(_item.resourceSinkPoints && _item.resourceSinkPoints > -1) ? _item.resourceSinkPoints : '无法放置于槽中'
					}}
				</el-tag>
			</el-descriptions-item>
			<el-descriptions-item>
				<template #label>
					伤害
				</template>
				<el-tag :type="(_item.damage && _item.damage > -1) ? undefined : 'info'">{{ (_item.damage && _item.damage > -1) ? _item.damage : '/' }}</el-tag>
			</el-descriptions-item>
		</el-descriptions>
	</el-dialog>
</template>

<script lang="ts" setup>

import {getImage} from '@/utils/commonUtil'
import {computed, reactive, ref, watch} from 'vue'
import router from '@/router'
import {useRoute} from 'vue-router'
import {useRouteParamsStore} from '@/stores/modules/routeParams.store'
import {useUserCacheStore} from '@/stores/modules/userInfo.store'
import {cloneDeep} from 'lodash-es'
import {CACHE_DURATION} from '@/utils/constantsUtil'
import {getBuildingDetailByIdApi} from '@/api/gameData/item.api'

const route = useRoute()
const routeParamsStore = useRouteParamsStore()
const userCacheStore = useUserCacheStore()

interface Props {
	item?: ItemDetailVo
	itemId?: number
	visible?: boolean
}

const props = withDefaults(defineProps<Props>(), {
	visible: false
})

const emits = defineEmits<{
	(e: 'update:visible', value: boolean): void
	(e: 'close'): void
	(e: 'searchRecipe', params?: SearchRecipeRequest): void
}>()

const visibleInner = computed({
	get() {
		return props.visible
	},
	set(val) {
		emits('update:visible', val)
	}
})

const loading = ref(false)

const _item = reactive<ItemDetailVo>({
	id: undefined,
	itemName: undefined,
	description: undefined,
	image: undefined,
	fluid: undefined,
	stack: undefined,
	equipmentLocation: undefined,
	handmade: undefined,
	energy: undefined,
	resourceSinkPoints: undefined,
	damage: undefined,
	classificationId: undefined,
	sort: undefined,
	equippable: undefined,
	operator: undefined,
	createTime: undefined,
	updateTime: undefined
})

const resetItemInfo = () => {
	for (const key in _item) {
		_item[<keyof ItemDetailVo>key] = undefined
	}
}

const dialogClosed = () => {
	emits('close')
}

const toRecipe = (type: 'asProduct' | 'asMaterial') => {
	visibleInner.value = false
	switch (type) {
		case 'asProduct':
			emits('searchRecipe', {
				productItemId: _item.id,
				productBuildingId: undefined,
				materialItemId: undefined,
				productionBuildingId: undefined
			})
			if (route.name !== 'Recipe') {
				routeParamsStore.setParams({
					productItemId: _item.id
				}, 'Recipe')
				router.push({name: 'Recipe'})
			}
			break
		case 'asMaterial':
			emits('searchRecipe', {
				productItemId: undefined,
				productBuildingId: undefined,
				materialItemId: _item.id,
				productionBuildingId: undefined
			})
			if (route.name !== 'Recipe') {
				routeParamsStore.setParams({
					materialItemId: _item.id
				}, 'Recipe')
				router.push({name: 'Recipe'})
			}
			break
	}
}

watch([() => props.item, () => props.itemId], val => {
	resetItemInfo()
	const [item, itemId] = val
	// 优先使用传入的props.item，如果props.item为空，则使用props.itemId查询物品信息
	if (item) {
		Object.assign(_item, item)
		// 如果给了物品id，缓存中没有则加入，有则覆盖
		if (item.id && item.id > 0) {
			const itemCacheElement = userCacheStore.itemCache[item.id]
			if (itemCacheElement && itemCacheElement.expire && itemCacheElement.expire > Date.now()) {
				Object.assign(itemCacheElement, item)
			} else {
				userCacheStore.itemCache[item.id] = cloneDeep(item)
				userCacheStore.itemCache[item.id].expire = Date.now() + CACHE_DURATION.ITEM
			}
		}
	} else if (itemId && itemId > 0) {
		// 先尝试从缓存中获取物品信息
		const itemCacheElement = userCacheStore.itemCache[itemId]
		if (itemCacheElement && itemCacheElement.expire && itemCacheElement.expire > Date.now()) {
			Object.assign(_item, itemCacheElement)
		}
		// 如果缓存中没有，则查询物品信息，并加入缓存
		else {
			loading.value = true
			getBuildingDetailByIdApi(itemId).then(response => {
				Object.assign(_item, response.data)
				userCacheStore.itemCache[itemId] = response.data
				userCacheStore.itemCache[itemId].expire = Date.now() + CACHE_DURATION.ITEM
			}).finally(() => {
				loading.value = false
			})
		}
	}
})

</script>

<style lang="scss" scoped>
</style>
